import React, { useState, useEffect } from 'react';
import {
  StyleSheet,
  View,
  TouchableOpacity,
  ScrollView,
  Dimensions,
  Animated,
} from 'react-native';
import { MaterialCommunityIcons } from '@expo/vector-icons';

import { ThemedText } from '@/components/ThemedText';
import { useThemeColor } from '@/hooks/useThemeColor';

const SCREEN_WIDTH = Dimensions.get('window').width;

// 模拟AI推荐回复
const REPLY_SUGGESTIONS = [
  [
    '好的，我会准时到的！',
    '下午三点可以，我们在哪里见面呢？',
    '今天天气确实不错，很适合散步',
    '我很期待和您一起散步聊天',
  ],
  [
    '谢谢您的关心，我一定会注意防晒的',
    '好的，我会带上帽子的',
    '您真是太贴心了，谢谢提醒',
    '我已经准备好了，很期待今天的散步',
  ],
  [
    '这个太极拳教程看起来很专业',
    '谢谢分享，我会好好学习的',
    '您也在练太极拳吗？有什么心得可以分享？',
    '我一直想学太极拳，这个教程正合适',
  ],
  [
    '孩子真可爱，长得很像您',
    '谢谢分享这么可爱的照片',
    '孙子多大了？看起来很聪明的样子',
    '您一定是位幸福的祖父母',
  ],
];

interface AIReplyAssistantProps {
  onSelectReply: (reply: string) => void;
  lastMessage?: {
    text: string;
    sender: string;
    time: string;
  };
}

export function AIReplyAssistant({ onSelectReply, lastMessage }: AIReplyAssistantProps) {
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [fadeAnim] = useState(new Animated.Value(0));
  const tintColor = useThemeColor({}, 'tint');

  // 当收到新消息时，生成推荐回复
  useEffect(() => {
    if (lastMessage && lastMessage.sender === 'other') {
      generateSuggestions();
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true,
      }).start();
    } else {
      // 如果是自己发送的消息，隐藏推荐回复
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }).start();
    }
  }, [lastMessage]);

  // 生成推荐回复
  const generateSuggestions = () => {
    // 在实际应用中，这里应该根据消息内容调用AI生成回复
    // 这里使用模拟数据
    const randomIndex = Math.floor(Math.random() * REPLY_SUGGESTIONS.length);
    setSuggestions(REPLY_SUGGESTIONS[randomIndex]);
  };

  // 处理选择回复
  const handleSelectReply = (reply: string) => {
    onSelectReply(reply);
    // 选择后隐藏推荐
    Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 200,
      useNativeDriver: true,
    }).start();
  };

  // 如果没有对方的消息，不显示组件
  if (!lastMessage || lastMessage.sender !== 'other') {
    return null;
  }

  return (
    <Animated.View 
      style={[styles.container, { opacity: fadeAnim }]}
      pointerEvents={lastMessage?.sender === 'other' ? 'auto' : 'none'}
    >
      <View style={styles.header}>
        <ThemedText style={styles.headerText}>AI推荐回复</ThemedText>
        <TouchableOpacity 
          style={styles.refreshButton}
          onPress={generateSuggestions}
        >
          <MaterialCommunityIcons name="refresh" size={18} color={tintColor} />
        </TouchableOpacity>
      </View>
      <ScrollView 
        horizontal 
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.suggestionsContainer}
      >
        {suggestions.map((suggestion, index) => (
          <TouchableOpacity
            key={index}
            style={[styles.suggestionItem, { borderColor: tintColor }]}
            onPress={() => handleSelectReply(suggestion)}
            activeOpacity={0.7}
          >
            <ThemedText style={styles.suggestionText}>{suggestion}</ThemedText>
          </TouchableOpacity>
        ))}
      </ScrollView>
    </Animated.View>
  );
}

const styles = StyleSheet.create({
  container: {
    marginHorizontal: 10,
    marginBottom: 10,
    backgroundColor: 'rgba(240, 240, 240, 0.8)',
    borderRadius: 15,
    padding: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  headerText: {
    fontSize: 14,
    fontWeight: '600',
    color: '#666',
  },
  refreshButton: {
    padding: 5,
  },
  suggestionsContainer: {
    paddingRight: 10,
  },
  suggestionItem: {
    backgroundColor: 'white',
    borderRadius: 18,
    borderWidth: 1,
    borderColor: '#1E88E5',
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginRight: 10,
    maxWidth: SCREEN_WIDTH * 0.7,
  },
  suggestionText: {
    fontSize: 15,
  },
});